package com.hoperun.framework.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import com.hoperun.framework.util.Constant;

public class CaptchaFormAuthenticationFilter extends FormAuthenticationFilter {

	/**
	 * 所有被拦截的请求都会经过的方法。
	 * 
	 * @return
	 */
	@Override
	public boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		HttpServletRequest httpservletrequest = (HttpServletRequest) request;
		String resUrl = httpservletrequest.getServletPath();
		if (resUrl.indexOf(super.getLoginUrl()) < Constant.ZERO) {
			// 初始化历史记录栈
			// LinkedList<String> historyUrlList = new LinkedList<String>();
			// historyUrlList.addFirst(resUrl);
			// httpservletrequest.getSession().setAttribute("historyUrlList",
			// historyUrlList);
			String queryString = httpservletrequest.getQueryString();
			String nextUrl = StringUtils.isBlank(queryString) ? resUrl : resUrl
					+ "?" + queryString;
			HttpSession session = httpservletrequest.getSession();
			session.setAttribute(Constant.REFERER, nextUrl);
		}
		saveRequestAndRedirectToLogin(request, response);
		return false;
	}

	@Override
	protected void issueSuccessRedirect(ServletRequest request,
			ServletResponse response) throws Exception {
		HttpServletRequest httpservletrequest = (HttpServletRequest) request;
		String resUrl = httpservletrequest.getServletPath();
		if (resUrl.indexOf(super.getLoginUrl()) < Constant.ZERO) {
			// 初始化历史记录栈
			// LinkedList<String> historyUrlList = new LinkedList<String>();
			// historyUrlList.addFirst(resUrl);
			// httpservletrequest.getSession().setAttribute("historyUrlList",
			// historyUrlList);
			String queryString = httpservletrequest.getQueryString();
			String nextUrl = StringUtils.isBlank(queryString) ? resUrl : resUrl
					+ "?" + queryString;
			HttpSession session = httpservletrequest.getSession();
			session.setAttribute(Constant.REFERER, nextUrl);
		}
		super.issueSuccessRedirect(request, response);
	}
}
